import subprocess
import re, os
from libs.mypthon import DEFINE


# 创建纯色空白视频
def make_blank_video(save_video_filename, need_timesec, color_hexadecimal, width, height, framerate=25):
    '''

    :param save_video_filename:
    :param need_timesec: int(单位秒
    :param color_hexadecimal:
    :param width:
    :param height:
    :param framerate:
    :return:
    '''
    # ffmpeg创建纯色空白视频命令
    # ffmpeg - ss 0 - t 30 - f lavfi - i color = c = 0x0000ff:s = 1280 x720: r = 25 - vcodec libx264 - r: v 25 test.mp4
    # -y强制覆盖
    arg = r'-y -hwaccel qsv -ss 0 -t {} -f lavfi -i color=c={}:s={}x{}:r={} -vcodec h264_qsv -r:v {} "{}"'.format(need_timesec,
                                                                                                  color_hexadecimal,
                                                                                                  width, height,
                                                                                                  framerate, framerate,
                                                                                                  save_video_filename)

    print(arg)
    ffmpeg_path = DEFINE.DIN_FFMPEG_PATH
    # print(ffmpeg_path)
    # 创建进程
    ffmpeg = subprocess.Popen('{} {}'.format(ffmpeg_path, arg), shell=True, stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)

    # 进程id
    id = ffmpeg.pid
    # 阻塞
    out, err = ffmpeg.communicate()
    if str(type(err)) == "<class 'bytes'>":
        arg_str = str(err, 'utf-8')
    else:
        arg_str = str(err)
    print(err)
    retcode = ffmpeg.poll()
    return {DEFINE.KEY_PID: id, DEFINE.KEY_RETCODE: retcode, DEFINE.KEY_OUTINFO: arg_str}

def make_blank_video_formAll(save_video_filename, need_timesec, color_hexadecimal, audiofile,subtitles_list, drawtext_text,drawtext_fontsize,drawtext_color,width, height, framerate=25):
    arg_0=[]
    if len(str(audiofile))!=0:
        arg_0.append('-i "{}" '.format(audiofile))
    vf_arg = []
    vf_arg.append('-vf ')
    for item in subtitles_list:
        vf_arg.append('subtitles="{}",'.format(item))
    if (len(drawtext_color) != 0) and (len(drawtext_text) != 0) and (len(str(drawtext_fontsize)) != 0):
        vf_arg.append(
            '''drawtext="fontfile='simkai.ttf':text='{}':y=h-line_h-10:x=(mod(2*n\,w+tw)-tw):fontsize={}:fontcolor={}:shadowy=1" '''.format(
                drawtext_text, drawtext_fontsize, drawtext_color))
    # arg.append('-vf subtitles="",subtitles="",drawtext="fontfile=simkai.ttf:text=你好123tyuioc:y=h-line_h-10:x=(mod(2*n\,w+tw)-tw):fontsize=24:fontcolor=#000000:shadowy=1"  ')
    if ''.join(vf_arg) != '-vf':
        arg_0.append(''.join(vf_arg))

    arg = r'-y -hwaccel qsv -f lavfi -i color=c={2}:s={3}x{4}:r={5} -r:v {6} {0} -ss 0 -t {1} -vcodec h264_qsv "{7}"'.format(
        ' '.join(arg_0),
        need_timesec,
        color_hexadecimal,
        width, height,
        framerate, framerate,
        save_video_filename)
    print(arg)
    ffmpeg_path = DEFINE.DIN_FFMPEG_PATH
    # ffmpeg_path=r'D:\myproject\python_project\Application_project\jingting\libs\ffmpeg\ffmpeg.exe'
    # print(ffmpeg_path)
    # 创建进程
    ffmpeg = subprocess.Popen('{} {}'.format(ffmpeg_path, arg), shell=True,    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE)
    # stdout = subprocess.PIPE,
    # stderr = subprocess.PIPE
    # 进程id
    id = ffmpeg.pid
    print(id)
    # 阻塞
    out, err = ffmpeg.communicate()
    if str(type(err)) == "<class 'bytes'>":
        arg_str = str(err, 'utf-8')
    else:
        arg_str = str(err)
    print(err)
    retcode = ffmpeg.poll()
    return {DEFINE.KEY_PID: id, DEFINE.KEY_RETCODE: retcode, DEFINE.KEY_OUTINFO: arg_str}

# 创建图片空白视频
def make_pic_video(pic_file, need_time, save_video, width=0, heigth=0, Framerate=25):
    '''

    :param pic_file:
    :param need_time:
    :param save_video:
    :param width: int(宽度,高度不赋值或者为0,则使用图片原分辨率;若只赋值一个则使用此数据进行等比缩放
    :param heigth: int(
    :param Framerate:
    :return:
    '''
    # ffmpeg -y -r 25 -loop 1 -i %d.jpeg -c:v libx265 -t 60 output1.mp4
    # -s 640x480 分辨率
    # -vf scale=-1:480 等比缩放
    arg = []
    # arg='-y -r 25 -loop 1 -i F:/test.jpg -t 10 F:/pic.mp4'
    arg.append('-y ')
    #
    arg.append('-hwaccel qsv ')
    # 图片,时间
    arg.append('-loop 1 -i "{}" -t {} '.format(pic_file, need_time))
    # 帧率
    arg.append('-r {} '.format(Framerate))
    # 分辨率
    if width != 0 and heigth != 0:
        arg.append('-s {}x{} '.format(width, heigth))
    elif width != 0 and heigth == 0:
        arg.append('-vf scale={}:-1 '.format(width))
    elif heigth != 0 and width == 0:
        arg.append('-vf scale=-1:{} '.format(heigth))
    arg.append('-vcodec h264_qsv ')
    arg.append('-threads 5 -preset veryfast ')
    # 输出文件
    arg.append('"{}"'.format(save_video))
    argstr = ' '.join(arg)
    print(argstr)
    # 创建进程
    # ffm = r'D:\myproject\python_project\Application_project\jingting\libs\ffmpeg\ffmpeg.exe'
    ffm= DEFINE.DIN_FFMPEG_PATH
    # print(ffm)
    ffmpeg = subprocess.Popen('{} {}'.format(ffm, argstr), shell=True,  stdout = subprocess.PIPE,
    stderr = subprocess.PIPE )
    # stdout = subprocess.PIPE,
    # stderr = subprocess.PIPE

    # 进程id
    id = ffmpeg.pid
    # 阻塞
    out, err = ffmpeg.communicate()
    if str(type(err)) == "<class 'bytes'>":
        arg_str = str(err, 'utf-8')
    else:
        arg_str = str(err)
    retcode = ffmpeg.poll()
    return {DEFINE.KEY_PID: id, DEFINE.KEY_RETCODE: retcode, DEFINE.KEY_OUTINFO: arg_str}

# 创建图片空白视频(图片,多字幕,音频,水印)
def make_pic_video_formAll(pic_file, need_time,audiofile,subtitles_list, drawtext_text,drawtext_fontsize,drawtext_color,save_video, width=0, heigth=0, Framerate=25):
    arg = []
    # arg='-y -r 25 -loop 1 -i F:/test.jpg -t 10 F:/pic.mp4'
    arg.append('-y ')
    arg.append('-hwaccel qsv ')
    #音频
    if len(audiofile)!=0:
        arg.append('-i "{}" '.format(audiofile))
    # 图片,时间
    arg.append('-loop 1 -i "{}" -t {} '.format(pic_file, need_time))
    # 帧率
    arg.append('-r {} '.format(Framerate))
    # 分辨率
    if width != 0 and heigth != 0:
        arg.append('-s {}x{} '.format(width, heigth))
    elif width != 0 and heigth == 0:
        arg.append('-vf scale={}:-1 '.format(width))
    elif heigth != 0 and width == 0:
        arg.append('-vf scale=-1:{} '.format(heigth))
    # 字幕,水印
    # -vf arg
    vf_arg=[]
    vf_arg.append('-vf ')
    for item in subtitles_list:
        vf_arg.append('subtitles="{}",'.format(item))
    if (len(drawtext_color)!=0)and(len(drawtext_text)!=0)and(len(str(drawtext_fontsize))!=0):
        vf_arg.append('''drawtext="fontfile='simkai.ttf':text='{}':y=h-line_h-10:x=(mod(2*n\,w+tw)-tw):fontsize={}:fontcolor={}:shadowy=1" '''.format(drawtext_text,drawtext_fontsize,drawtext_color))
    # arg.append('-vf subtitles="",subtitles="",drawtext="fontfile=simkai.ttf:text=你好123tyuioc:y=h-line_h-10:x=(mod(2*n\,w+tw)-tw):fontsize=24:fontcolor=#000000:shadowy=1"  ')
    if ''.join(vf_arg)!='-vf':
        arg.append(''.join(vf_arg))

    arg.append('-vcodec h264_qsv ')
    # arg.append('-preset veryfast ')
    # 输出文件
    arg.append('"{}"'.format(save_video))
    argstr = ' '.join(arg)
    print(argstr)
    # 创建进程
    # ffm = r'D:\myproject\python_project\Application_project\jingting\libs\ffmpeg\ffmpeg.exe'
    ffm= DEFINE.DIN_FFMPEG_PATH
    # print(ffm)
    ffmpeg = subprocess.Popen('{} {}'.format(ffm, argstr), shell=True,  stdout = subprocess.PIPE,
    stderr = subprocess.PIPE )
    # stdout = subprocess.PIPE,
    # stderr = subprocess.PIPE
    # 进程id
    id = ffmpeg.pid
    # 阻塞
    out, err = ffmpeg.communicate()
    if str(type(err)) == "<class 'bytes'>":
        arg_str = str(err, 'utf-8')
    else:
        arg_str = str(err)
    retcode = ffmpeg.poll()
    return {DEFINE.KEY_PID: id, DEFINE.KEY_RETCODE: retcode, DEFINE.KEY_OUTINFO: arg_str}

# 视频添加字幕
def add_ass_forVideo(videofile, subtitlefile, save_videofile):
    # ffmpeg 添加硬字幕命令
    # ffmpeg -i test_1280x720_3.mp4 -vf subtitles=test_1280x720_3.srt out.mp4
    # 软字幕 .mkv
    # ffmpeg -i test_1280x720_3.mkv -i test_1280x720_3.srt -c copy output.mkv

    # 后缀
    name, suffix = os.path.splitext(os.path.basename(videofile))
    if suffix == '.mkv' or suffix == '.MKV':
        arg = r'-y -hwaccel qsv -i "{}" -i "{}" -c copy -vcodec h264_qsv "{}"'.format(videofile, subtitlefile, save_videofile)
    else:
        arg = r'-y -hwaccel qsv -i "{}" -vf subtitles="{}" -vcodec h264_qsv "{}"'.format(videofile, subtitlefile, save_videofile)
    # ffmpegpath=DEFINE.DIN_FFMPEG_PATH
    ffmpegpath=r'D:\myproject\python_project\Application_project\jingting\libs\ffmpeg\ffmpeg.exe'
    # 创建进程
    ffmpeg = subprocess.Popen('{} {}'.format(ffmpegpath, arg), shell=True, stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)
    #
    # 进程id
    id = ffmpeg.pid
    print(id)
    # 阻塞
    out, err = ffmpeg.communicate()
    if str(type(err)) == "<class 'bytes'>":
        arg_str = str(err, 'utf-8')
    else:
        arg_str = str(err)
    print(arg_str)
    retcode = ffmpeg.poll()
    return {DEFINE.KEY_PID: id, DEFINE.KEY_RETCODE: retcode, DEFINE.KEY_OUTINFO: arg_str}

# 视频添加音频
def add_audio_forVideo(videofile, audiofile, save_videofile):
    # ffmpeg 命令
    # ffmpeg -an -i video.mp4 -stream_loop -1 -i audio.wav -t 60 -y out2.mp4
    bo_sucess, time_len = getVideoTime(videofile)
    if not bo_sucess:
        return {DEFINE.KEY_PID: -1, DEFINE.KEY_RETCODE: -1,
                DEFINE.KEY_OUTINFO: 'add_audio_forVideo(videofile, audiofile, save_videofile):getVideoTime失败'}
    arg = r'-y -hwaccel qsv -an -i "{}" -stream_loop -1 -i "{}" -t {} -vcodec h264_qsv "{}"'.format(videofile, audiofile, time_len, save_videofile)
    # 创建进程
    # ffm=  r'D:\myproject\python_project\Application_project\jingting\libs\ffmpeg\ffmpeg.exe'
    # print(ffm)
    ffm= DEFINE.DIN_FFMPEG_PATH
    ffmpeg = subprocess.Popen('{} {}'.format(ffm, arg), shell=True, stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)
    # 进程id
    id = ffmpeg.pid
    print(id)
    # 阻塞
    out, err = ffmpeg.communicate()
    if str(type(err)) == "<class 'bytes'>":
        arg_str = str(err, 'utf-8')
    else:
        arg_str = str(err)
    retcode = ffmpeg.poll()
    return {DEFINE.KEY_PID: id, DEFINE.KEY_RETCODE: retcode, DEFINE.KEY_OUTINFO: arg_str}

# 获取视频时长(00:01:00.02)
def getVideoTime(videofile):
    '''
    # 获取视频时长(00:01:00.02)
    #测试了音频输出也是如此,所以可获取音频时长
    :param videofile:
    :return: str(00:01:00.02)
    '''
    # ffmpeg -i d://a.mp4
    # Duration: 00:05:29.20, start: 0.000000, bitrate: 377 kb/s
    # Duration: 00:01:00.02, start: 0.000000, bitrate: 143 kb/s
    # 测试了音频输出也是如此,所以可获取音频时长
    # Duration: 00:03:18.79, start: 0.025057, bitrate: 99 kb/s
    arg = r'-i "{}"'.format(videofile)
    # 创建进程
    # 十分注意DEFINE.DIN_FFMPEG_PATH 的位置是否正确
    # ffmpegPath=r'D:\myproject\python_project\Application_project\jingting\libs\ffmpeg\ffmpeg.exe'
    ffmpegPath= DEFINE.DIN_FFMPEG_PATH
    ffmpeg = subprocess.Popen(
        '{} {}'.format(ffmpegPath, arg),
        shell=True, stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    # 进程id
    id = ffmpeg.pid
    # 阻塞
    out, err = ffmpeg.communicate()
    if str(type(err)) == "<class 'bytes'>":
        arg_str = str(err, 'utf-8')
    else:
        arg_str = str(err)
    # 正则表达式
    pattern = re.compile('Duration: [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9]')
    # print(arg_str)
    ob = re.search(pattern, arg_str)
    if ob == None:
        return False, '无时间信息:{}'.format(arg_str)
    else:
        ret_time = ob.group()
        ret_time = ret_time.replace('Duration: ', '')
        return True, ret_time


# 添加水印
def add_textlogo_forVideo(video, text, fontsize, fontcolor, savefile):
    # fontfile的路径是windows 传入时先要 将\ 转换为 \\
    fontfile='simkai.ttf'
    # ffmpeg -y -i  H:/t1.mp4 -vf "drawtext=fontfile=='技术是第一生产力 | 制作: 精听UP-MaofU':y=h-line_h-10:x=(mod(2*n\,w+tw)-tw):fontsize=24:fontcolor=black:shadowy=1" H:/test.mp4
    arg = '''-y -hwaccel qsv -i  '{}' -vf drawtext="fontfile='{}':text='{}':y=h-line_h-10:x=(mod(2*n\,w+tw)-tw):fontsize={}:fontcolor={}:shadowy=1" -vcodec h264_qsv '{}' '''.format(
        video, fontfile, text, fontsize, fontcolor, savefile)
    print(arg)
    # ffmpeg_path = DEFINE.DIN_FFMPEG_PATH
    ffmpeg_path = r'/pyQt/libs/ffmpeg/ffmpeg.exe'
    # print(ffmpeg_path)
    # 创建进程
    ffmpeg = subprocess.Popen('{} {}'.format(ffmpeg_path, arg), shell=True, stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)

    # 进程id
    id = ffmpeg.pid
    print(id)
    # 阻塞
    out, err = ffmpeg.communicate()
    if str(type(err)) == "<class 'bytes'>":
        arg_str = str(err, 'utf-8')
    else:
        arg_str = str(err)
    print(arg_str)
    retcode = ffmpeg.poll()
    return {DEFINE.KEY_PID: id, DEFINE.KEY_RETCODE: retcode, DEFINE.KEY_OUTINFO: arg_str}


def audio_compress(audieo,savefile):
    # ffmpeg -i input.mp3 -codec:a libmp3lame -b:a 128k output.mp3
    # ffmpeg -i "1.wav" -b:a 64k -acodec mp3 -ar 44100 -ac 1 "1.mp3
    arg='-y -i "{0}" -f mp3 -vn "{1}"'.format(audieo,savefile)
    ffmpeg_path = DEFINE.DIN_FFMPEG_PATH
    # ffmpeg_path = r'D:\myproject\python_project\Application_project\jingting\libs\ffmpeg\ffmpeg.exe'
    # print(ffmpeg_path)
    # 创建进程
    ffmpeg = subprocess.Popen('{} {}'.format(ffmpeg_path, arg), shell=True, stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)

    # 进程id
    id = ffmpeg.pid
    # 阻塞
    out, err = ffmpeg.communicate()
    if str(type(err)) == "<class 'bytes'>":
        arg_str = str(err, 'utf-8')
    else:
        arg_str = str(err)
    print(arg_str)
    retcode = ffmpeg.poll()
    return {DEFINE.KEY_PID: id, DEFINE.KEY_RETCODE: retcode, DEFINE.KEY_OUTINFO: arg_str}

if __name__ == '__main__':
    # make_blank_video()
    # make_blank_video_formAll('F:/blank.mp4',50,'#FFEFD5','F:/test.mp3',['../../jingting_tempFiles/Make_video_sequentially/videoSubtitle.ass','../../jingting_tempFiles/Make_video_sequentially/OptionSubtit.ass'],"《六级英语听力真题：2021年06月第2套》【制作：精听UP-MaofU】如果视频有用的话，那还请多多支持鸭o(〃'▽'〃)o",24,'#000000',1920,1080)
    add_ass_forVideo(r'D:\myproject\python_project\Application_project\jingting\saveVideofilePath\23_2020年12月大学英语六级听力真题（第二套）_mp3.mp4', '字幕.ass', 'H:/add_ass.mp4')
    # add_audio_forVideo('F:/add_ass.mp4', 'F:/test.mp3', 'F:/add_audio.mp4')
    # make_pic_video('F:/test.jpg',10,'F:/pic.mp4',1080,720)
    # di=make_pic_video('F:/风景意大利.png', '00:01:00.02', 'F:/pic.mp4', 0, 0)
    # di=make_pic_video_formAll('F:/风景意大利.png', '00:01:00.02','F:/test.mp3',['../../jingting_tempFiles/Make_video_sequentially/videoSubtitle.ass','../../jingting_tempFiles/Make_video_sequentially/OptionSubtit.ass'],'jingting精听up',24,'#000000','F:/pic.mp4')
    # di=add_textlogo_forVideo('H:/t1.mp4','精听up|MaofU',r'',24,'#000000','H:/test.mp4')
    # text=di[DEFINE.KEY_OUTINFO]
    # print(text)
    # bo,time=getVideoTime(r'F:\四六级\六级\xin音频\2021年12月六级听力第一套 00_00_13-00_26_27.mp3')
    # print(time)
    # audio_compress('H:/test.mp3','H:/compress.mp3')